package czk.concrent.immutableClass;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * DateTimeFormatter jdk1.8提供的线程安全的类
 * @Author:ChenZhangKun
 * @Date: 2020/6/20 20:19
 */
public class DateTimeFormatterTest {
    public static void main(String[] args) throws InterruptedException {
        // jdk1.8依旧提供的类，线程安全的
        DateTimeFormatterTest dateTimeFormatterTest=new DateTimeFormatterTest();
        // jdk 1.8以前提供的类，属于线程不全的类，有线程安全问题
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i <10 ; i++) {
            new Thread(()->{
                dateTimeFormatterTest.test();
            }).start();
        }
        Thread.sleep(2*1000);
        // 测试以前的类有没有指令交错问题,此时会抛出异常
        // 加上锁后没有指令交错则不会报错
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    synchronized (DateTimeFormatterTest.class){
                        Date parse = simpleDateFormat.parse("2020-06-21");
                        System.out.println(parse);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
    public void test(){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        TemporalAccessor parse = dateTimeFormatter.parse("2020-06-20");
        System.out.println(parse);
    }
}
